import {HttpException, HttpStatus, Injectable} from "@nestjs/common";
import {Express} from "express"
import * as path from "path"
import * as fs from "fs-extra"
import * as moment from "moment"
import IHelper from "@/services/helper.service";
import IConstants from "@/core/constants";
import IResponse from "@/services/response.service";
import {ConfigService} from "@nestjs/config";
import {ReqProvider} from "@/core/providers/req.provider";
import { Observable, defer, delay, map, tap, of, concatMap, from } from "rxjs";
import * as lineReader from "line-reader"
import * as puppeteer from "puppeteer"
import { RedisProvider } from "@/core/providers/redis.provider";
import * as sharp from "sharp"
import * as shelljs from "shelljs"
import { IWonewSer } from "@/typing";
import IFfmpeg from "@/services/ffmpeg.service";
import { SyncEmailService } from "../sync-email/sync-email.service";

@Injectable()
export class SharedService {
  constructor(
    private readonly configService: ConfigService,
    private readonly reqProvider: ReqProvider,
    private readonly redisProvider: RedisProvider,
    private readonly syncEmailService: SyncEmailService,
  ) {
    fs.ensureDirSync(path.join(IConstants.publicDir, "uploads"))
  }
  upload(file: Express.Multer.File) {
    const ALLOW_EXT_LIST: string[] = [".JPG", ".PNG", ".JPEG", ".MP4"]
    const MAX_SIZE: number = 500 * 1000 * 1000
    const extname = path.extname(file.originalname)
    if (file.size > MAX_SIZE) {
      throw new HttpException("File size cannot exceed 5M", HttpStatus.BAD_REQUEST)
    }
    if (!ALLOW_EXT_LIST.includes(extname.toUpperCase())) {
      throw new HttpException("The extname not supported to upload.", HttpStatus.BAD_REQUEST)
    }
    const relativePath = path.join("uploads", moment().format("YYYY/MM/DD"), `${IHelper.hash(32)}${extname}`)
    const absoluteFilepath = path.join(IConstants.publicDir, relativePath)
    fs.ensureFileSync(absoluteFilepath)
    fs.writeFileSync(absoluteFilepath, file.buffer)
    const url = path.join(this.configService.get("STATIC_PREFIX", "static"), relativePath)
    const finalUrl = ["", ...url.split(path.sep)].join("/")
    return of(null).pipe(
      delay(1000),
      map(() => IResponse.success({ url: finalUrl }))
    )
    // return IResponse.success({ url: finalUrl })
  }

  renderPuppeteerScreenshot(opt: {id: string, text: string, video_size: string}) {
    return defer(() => 
      this.redisProvider.get<any>(opt.id)
    ).pipe(
      map(data => data)
    )
  }

  debug(id: number) {
    return this[`debug${id}`]()
  }

  debug1() {
    return {ho: moment().hours()}
  }
}